package org.grayrabbit.cloud.core.module;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cloud.core.biz.BizAbstractModule;
import org.grayrabbit.cloud.core.biz.BizArgument;
import org.grayrabbit.cloud.core.biz.BizResult;
import org.grayrabbit.cloud.core.biz.ProxyArgument;
import org.grayrabbit.cloud.core.rpc.Argument;
import org.grayrabbit.cloud.core.rpc.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ProxyModule extends BizAbstractModule {
	private static Logger logger = LoggerFactory.getLogger(ProxyModule.class);
	@Override
	public Result submit(Argument argument) throws ModuleException {
		if (argument instanceof BizArgument) {
			if(argument instanceof ProxyArgument){//新部署的远程服务注册到本代理服务器上
				ProxyArgument arg = (ProxyArgument) argument;
				logger.info("代理业务模块{}-{}加载...",arg.getModuleName(),arg.getRemoteAddr());
				if(StringUtils.isNotBlank(arg.getModuleName())){
					@SuppressWarnings("unchecked")
					List<String> modules = (List<String>)arg.getObject();
					for(String m : modules){
						if(StringUtils.isNotBlank(m)){
							Proxy<BizResult,BizArgument> proxy = new RemoteModule(m,arg.getRemoteAddr());
							ProxyModuleContext.getInstance().setValue(m, proxy);
							logger.info("代理业务模块{}-{}加载完成!",m,arg.getRemoteAddr());
						}
					}
				}
				return BizResult.TRUE;//注册成功
			}else{
				logger.info("代理请求!");
				BizArgument arg = (BizArgument) argument;
				return ProxyModuleContext.getInstance().getValue(arg.getCmdParams().get("module")).submit(arg);
			}
		} 
		return null;
	}
}
